package org.zerofwk.example.datastruct.stack;

public class StackTest {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(7);

        System.out.println("入栈测试：");
        arrayStack.push(10);
        arrayStack.push(13);
        arrayStack.push(14);
        arrayStack.push(15);
        arrayStack.push(16);
        arrayStack.push(18);
        arrayStack.show();

        System.out.println("出栈测试：");
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
        System.out.printf("出栈元素：%d\n",arrayStack.pop());
    }


    private static class ArrayStack {
        private int top = -1;
        private int maxSize = 0;
        private int[] statck;

        public ArrayStack(int maxSize) {
            this.maxSize = maxSize;
            statck = new int[maxSize];
        }

        public boolean isFull() {
            return top == maxSize - 1;
        }

        public boolean isEmpty() {
            return top == -1;
        }

        public void push(int newVal) {
            if (isFull()) {
                System.out.println("栈满。");
                return;
            }
            top++;
            statck[top] = newVal;
        }

        public int pop() {
            if (isEmpty()) {
                throw new RuntimeException("栈空。");
            }
            int retVal = statck[top];
            top--;
            return retVal;
        }

        public void show() {
            if (isEmpty()) {
                System.out.println("栈空。");
                return;
            }
            for (int i = top; i >= 0; i--) {
                System.out.printf("栈内元素stack[%d]=%d\n",i,statck[i]);
            }
        }
    }
}


